<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>船舶管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!--    <link rel="stylesheet" href="../web/resource/css/allcss/allCss.css" type="text/css">-->
    <style>

    </style>
</head>
<body>
<div class="query-container">
    <div class="form-row">
        <div class="form-item">
            <label class="form-label">所属供应商：</label>
            <select class="form-input form-select-supplier" id="form-select-supplier">
                <option value="">全部</option>
            </select>
        </div>
<!--        <div class="form-item">-->
<!--            <label class="form-label">司机：</label>-->
<!--            <input type="text"-->
<!--                   class="form-input"-->
<!--                   placeholder="请输入司机姓名">-->
<!--        </div>-->
        <div class="form-item">
            <label class="form-label">船名：</label>
            <input type="text"
                   class="form-input"
                   placeholder="请输入船名">
        </div>
<!--        <div class="form-item">-->
<!--            <label class="form-label">启用状态：</label>-->
<!--            <select class="form-input form-select-car-isEnable">-->
<!--                <option value="">全部</option>-->
<!--                <option value="1">启用</option>-->
<!--                <option value="0">禁用</option>-->
<!--            </select>-->
<!--        </div>-->
<!--        <div class="form-item">-->
<!--            <label class="form-label">出车状态：</label>-->
<!--            <select class="form-input form-select-car-status">-->
<!--                <option value="">全部</option>-->
<!--                <option value="0">空闲中</option>-->
<!--                <option value="1">运输中</option>-->
<!--                <option value="2">故障</option>-->
<!--            </select>-->
<!--        </div>-->
    </div>
    <!-- 操作按钮 -->
    <div class="action-buttons">
        <button class="btn btn-reset">重置</button>
        <button class="btn btn-query">查询</button>
        <button class="btn btn-add">新增</button>
    </div>
</div>
<div class="table-container">
    <table class="data-table">
        <thead class="data-table-thead">
        <tr>
            <th>序号</th>
            <th>船名</th>
            <th>所属供应商</th>
            <th>联系方式</th>
            <th>出航状态</th>
            <th>车辆状态</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
    <!-- 分页 -->
</div>
<div class="pagination">
    <span>共0条</span>
    <select class="data-table-page" >
        <option class="" value="10" selected>10条/页</option>
        <option class="" value="20">20条/页</option>
        <option class="" value="50">50条/页</option>
    </select>
    <div class="page-num">
        <button class="pre-button">＜</button>
        <span>1</span>
        <button class="next-button">＞</button>
    </div>
</div>
<div class="modal-mask" id="modal-mask-add">
    <div class="modal-content">
        <h3 class="modal-title">
            新增供应商船舶 <!-- 修改标题 -->
            <button class="modal-close-btn">×</button>
        </h3>
        <form class="modal-form" id="modal-form-add">
            <!-- 所属供应商下拉 -->
            <div class="form-item">
                <label>所属供应商：</label>
                <select class="form-input" id="add-supplierId" required> <!-- ID改为supplierId -->
                    <option value="">请选择供应商</option>
                    <!-- 动态加载供应商选项 -->
                </select>
            </div>

            <!-- 基础信息 -->

                <div class="form-item">
                    <label>船名：</label> <!-- 改为船名 -->
                    <input type="text" id="add-name" class="form-input" required>
                </div>
                <div class="form-item">
                    <label>联系电话：</label> <!-- 新增联系电话 -->
                    <input type="tel" id="add-phone" class="form-input" required>
                </div>


            <!-- 吨位信息 -->

                <div class="form-item">
                    <label>总吨：</label>
                    <input type="number" id="add-grossTon" class="form-input" step="0.1" required>
                </div>
                <div class="form-item">
                    <label>载重吨：</label>
                    <input type="number" id="add-loadTon" class="form-input" step="0.1" required>
                </div>


            <!-- 船舶尺寸 -->
            <div class="form-row">
                <div class="form-item">
                    <label>船舶尺寸(m)：</label>
                    <div class="dimension-group">
                        <input type="number" id="add-longSize" class="form-input" placeholder="长" step="0.1" required>
                        <input type="number" id="add-widthSize" class="form-input" placeholder="宽" step="0.1" required>
                        <input type="number" id="add-heightSize" class="form-input" placeholder="高" step="0.1" required>
                    </div>
                </div>
            </div>

            <div class="modal-buttons">
                <button type="button" class="btn-close">关闭</button>
                <button type="submit" class="btn-submit">新增</button>
            </div>
        </form>
    </div>
</div>

<!-- 将modal-title改为"修改船舶信息" -->
<div class="modal-mask" id="modal-mask-update">
    <div class="modal-content">
        <h3 class="modal-title">
            修改船舶信息
            <button class="modal-close-btn">×</button>
        </h3>
        <form class="modal-form" id="modal-form-update">
            <!-- 所属供应商 -->
            <div class="form-item">
                <label>所属供应商：</label>
                <select class="form-input" id="update-supplierId" required>
                    <option value="">请选择供应商</option>
                    <!-- 动态加载选项 -->
                </select>
            </div>

            <!-- 基础信息 -->

                <div class="form-item">
                    <label>船名：</label>
                    <input type="text" id="update-name" required>
                </div>
                <div class="form-item">
                    <label>联系电话：</label>
                    <input type="tel" id="update-phone" required>
                </div>


            <!-- 吨位信息 -->

                <div class="form-item">
                    <label>总吨：</label>
                    <input type="number" id="update-grossTon" step="0.1" required>
                </div>
                <div class="form-item">
                    <label>载重吨：</label>
                    <input type="number" id="update-loadTon" step="0.1" required>
                </div>


            <!-- 船舶尺寸 -->

                <div class="form-item">
                    <label>船舶尺寸(m)：</label>
                    <div class="dimension-group">
                        <input type="number" id="update-longSize" placeholder="长" step="0.1" required>
                        <input type="number" id="update-widthSize" placeholder="宽" step="0.1" required>
                        <input type="number" id="update-heightSize" placeholder="高" step="0.1" required>
                    </div>
                </div>


            <div class="modal-buttons">
                <button type="button" class="btn-close">关闭</button>
                <button type="submit" class="btn-submit">保存</button>
            </div>
        </form>
    </div>
</div>
<div class="modal-mask" id="modal-mask-detail">
    <div class="modal-content">
        <h3 class="modal-title">
            船舶详情 <!-- 修改标题 -->
            <button class="modal-close-btn">×</button>
        </h3>
        <div class="modal-body">
            <!-- 基础信息 -->
            <div class="detail-section">
                <h4 class="detail-subtitle">基础信息</h4>
                <div class="detail-row">
                    <span class="detail-label">所属供应商：</span>
                    <span id="detail-supplierName" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">船名：</span>
                    <span id="detail-name" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">联系电话：</span>
                    <span id="detail-phone" class="detail-value"></span>
                </div>
            </div>

            <!-- 吨位信息 -->
            <div class="detail-section">
                <h4 class="detail-subtitle">吨位信息</h4>
                <div class="detail-row">
                    <span class="detail-label">总吨：</span>
                    <span id="detail-grossTon" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">载重吨：</span>
                    <span id="detail-loadTon" class="detail-value"></span>
                </div>
            </div>

            <!-- 船舶尺寸 -->
            <div class="detail-section">
                <h4 class="detail-subtitle">船舶尺寸</h4>
                <div class="detail-row">
                    <span class="detail-label">长×宽×高：</span>
                    <span id="detail-dimensions" class="detail-value"></span>
                </div>
            </div>

            <!-- 状态信息 -->
            <div class="detail-section">
                <h4 class="detail-subtitle">状态信息</h4>
                <div class="detail-row">
                    <span class="detail-label">出航状态：</span>
                    <span id="detail-status" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">启用状态：</span>
                    <span id="detail-isEnable" class="detail-value"></span>
                </div>
            </div>

            <!-- 操作记录 -->
            <div class="detail-section">
                <h4 class="detail-subtitle">操作记录</h4>
                <div id="detail-operationLogs" class="detail-logs">
                    <!-- 动态填充操作记录 -->
                </div>
            </div>
        </div>
        <div class="modal-buttons">
            <button type="button" class="btn-close">关闭</button>
        </div>
    </div>
</div>
<script>
    const nextButton = document.querySelector('.next-button')
    const preButton = document.querySelector('.pre-button')
    //渲染
    function renderTable(data) {
        document.querySelector('.pagination span:first-child')
            .textContent = `共${data.data.total}条`;
        const tbody = document.querySelector('.data-table tbody');

        // 更新页码显示
        document.querySelector('.page-num span').textContent = data.data.current;

        if (data.data.current >= data.data.pages){
            nextButton.disabled = true;
            nextButton.style.opacity = "0.5";
        }else {
            nextButton.disabled = false;
            nextButton.style.opacity = "1";
        }

        if (data.data.current <= 1){
            preButton.disabled = true;
            preButton.style.opacity = "0.5";
        }else {
            preButton.disabled = false;
            preButton.style.opacity = "1";
        }

        tbody.innerHTML = ''; // 清空旧数据
        data.data.records.
        slice( // 根据分页参数切割数据
            (data.data.current - 1)
            * data.data.size,
            data.data.current * data.data.size
        ).forEach((item, index) => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
            <td>${(data.data.current - 1) * data.data.size + index + 1}</td>
            <td>${item.name || '--'}</td>
            <td>${item.supplierName || '--'}</td>
            <td>${item.phone || '--'}</td>
            <td>${STATUS_MAP[item.status] || '未知'}</td>
            <td>${item.isEnable ===1 ? '已启用' : '已禁用'}</td>
            <td>
                <button class="table-disable-btn">${item.isEnable ===1 ? '禁用' : '启用'}</button>
                <button class="table-detail-btn">详情</button>
                <button class="table-edit-btn">修改</button>
                <button class="table-delete-btn">删除</button>
            </td>
        `;

            const detailBtn = tr.querySelector('.table-detail-btn');
            const disableBtn = tr.querySelector('.table-disable-btn');
            const editBtn = tr.querySelector('.table-edit-btn');
            const deleteBtn = tr.querySelector('.table-delete-btn');

            disableBtn.addEventListener('click', () => disableRole(item.id, item.isEnable));
            detailBtn.addEventListener('click', () => showHighDetail(item));
            editBtn.addEventListener('click', () => updateRole(item));
            deleteBtn.addEventListener('click', () => deleteCar(item.id));

            tbody.appendChild(tr);
        });
    }
    document.querySelector('.btn-query').addEventListener('click',function (){
        fetchData('query');
    })
    document.querySelector('.pre-button').addEventListener('click',function (){
        fetchData('pre');
    })
    document.querySelector('.next-button').addEventListener('click',function (){
        fetchData('next');
    })
    // 统一请求方法
    async function fetchData(type) {

        let { page, pageSize } = getPaginationParams();

        if (type === 'pre') {
            page = Math.max(1, page - 1)  // 确保页码不小于1
            document.querySelector('.page-num span').textContent = page  // 同步更新页码显示
        }else if (type === 'next'){
            page = Math.max(1, page + 1)  // 确保页码不小于1
            document.querySelector('.page-num span').textContent = page  // 同步更新页码显示
        }

        const queryParams = {
            supplierId: document.getElementById('form-select-supplier').value,
            // driverName: document.querySelector('input[placeholder="请输入司机姓名"]').value,
            name: document.querySelector('input[placeholder="请输入船名"]').value,
            // isEnable: document.querySelector('.form-select-car-isEnable').value,
            // status: document.querySelector('.form-select-car-status').value,
            page: page,
            rows: pageSize
        };

        try {
            const response = await fetch('http://localhost:8080/sys/ship/pageList', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(queryParams)
            });

            const data = await response.json();
            if (data.status === 0) {
                renderTable(data);
                // console.log(data.data)
            }else  if (data.status === -1) {
                console.error('请求失败:', error);
            }
        } catch (error) {
            console.error('请求失败:', error);
            renderTable({ data: { records: [], total: 0, current: 1, pages: 0 } });
        }
    }
    //重置按钮
    document.querySelector('.btn-reset').addEventListener('click',()=>{
        document.querySelectorAll('.form-input').forEach(input => {
            if (input.type === 'text') input.value = '';
            if (input.tagName === 'SELECT') input.value = '';
        });

    })
    //新增按钮相关
    // 显示弹窗
    document.querySelector('.btn-add').addEventListener('click', () => {
        document.querySelector('#modal-mask-add').style.display = 'flex'
    })
    // 关闭弹窗
    document.querySelectorAll('.modal-close-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            this.closest('.modal-mask').style.display = 'none';
        });
    });

    document.querySelectorAll('.btn-close').forEach(btn => {
        btn.addEventListener('click', function() {
            this.closest('.modal-mask').style.display = 'none';
        });
    });
    // 表单提交处理
    document.querySelector('#modal-form-add').addEventListener('submit', async (e) => {
        e.preventDefault();

        const formData = {
            supplierId: document.getElementById('add-supplierId').value,
            name: document.getElementById('add-name').value,
            phone: document.getElementById('add-phone').value,
            grossTon: parseFloat(document.getElementById('add-grossTon').value),
            loadTon: parseFloat(document.getElementById('add-loadTon').value),
            longSize: parseFloat(document.getElementById('add-longSize').value),
            widthSize: parseFloat(document.getElementById('add-widthSize').value),
            heightSize: parseFloat(document.getElementById('add-heightSize').value)
        };


        try {
            const response = await fetch('http://localhost:8080/sys/ship/add', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            });

            const data = await response.json();
            if (data.status === 0) {
                alert('添加成功');
                document.getElementById('modal-mask-add').style.display = 'none';
                document.getElementById('modal-form-add').reset();
                fetchData('query');
            } else {
                alert('添加失败：' + (data.message || '未知错误'));
            }
        } catch (error) {
            console.error('提交失败:', error);
            alert('提交失败：' + error.message);
        }
    });
    //表格函数
    async function showHighDetail(item) {
        const modal = document.getElementById('modal-mask-detail');
        try {
            document.getElementById('detail-operationLogs').innerHTML = "加载中...";

            const res = await fetch(`http://localhost:8080/sys/ship/detail/${item.id}`);
            const response = await res.json();

            if (response.status === 0) {
                const data = response.data;

                // 填充基础信息
                document.getElementById('detail-supplierName').textContent = data.supplierName || '--';
                document.getElementById('detail-name').textContent = data.name || '--';
                document.getElementById('detail-phone').textContent = data.phone || '--';

                // 吨位信息
                document.getElementById('detail-grossTon').textContent = data.grossTon ? `${data.grossTon}吨` : '--';
                document.getElementById('detail-loadTon').textContent = data.loadTon ? `${data.loadTon}吨` : '--';

                // 船舶尺寸
                const dimensions = `${data.longSize || 0} × ${data.widthSize || 0} × ${data.heightSize || 0}`;
                document.getElementById('detail-dimensions').textContent = dimensions;

                // 状态信息
                document.getElementById('detail-status').textContent = STATUS_MAP[data.status] || '未知';
                document.getElementById('detail-isEnable').textContent = data.isEnable === 1 ? '已启用' : '已禁用';

                // 操作记录处理
                const logsContainer = document.getElementById('detail-operationLogs');
                if (data.operateRecordList?.length > 0) {
                    logsContainer.innerHTML = data.operateRecordList.map(log => `
                    <div class="log-item">
                        <span class="log-time">${formatDateTime(log.createTime)}</span>
                        <span class="log-type">${log.operateType}</span>
                        ${log.remark ? `<span class="log-remark">（${log.remark}）</span>` : ''}
                    </div>
                `).join('');
                } else {
                    logsContainer.innerHTML = '<div class="no-data">暂无操作记录</div>';
                }

                modal.style.display = 'flex';
            }
        } catch (err) {
            console.error('详情加载失败:', err);
            document.getElementById('detail-operationLogs').innerHTML =
                '<div class="error-msg">记录加载失败</div>';
        }
    }
    async function disableRole(id, currentStatus) {
        const newStatus = currentStatus ? 0 : 1;
        try {
            const res = await fetch(`http://localhost:8080/sys/ship/disable`, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ id, isEnable: newStatus })
            });

            const data = await res.json();
            if(data.status === 0) {
                alert(`已${newStatus ? '启用' : '禁用'}`);
                fetchData('query');
            }
        } catch(err) {
            console.error('状态修改失败:', err);
            alert('状态修改失败，请检查网络连接');
        }
    }
    // 修改功能弹窗
    let currentEditHandler = null;
    // 修改功能（需要实现编辑弹窗）
    // 新增修改功能逻辑
    async function updateRole(item) {
        const modal = document.getElementById('modal-mask-update');
        try {
            const res = await fetch(`http://localhost:8080/sys/ship/detail/${item.id}`);
            const response = await res.json();

            if (response.status === 0) {
                const data = response.data;

                // 填充供应商下拉并设置选中值
                const supplierSelect = document.getElementById('update-supplierId');
                supplierSelect.value = data.supplierId;

                // 填充基础数据
                document.getElementById('update-name').value = data.name || '';
                document.getElementById('update-phone').value = data.phone || '';

                // 填充吨位数据
                document.getElementById('update-grossTon').value = data.grossTon || '';
                document.getElementById('update-loadTon').value = data.loadTon || '';

                // 填充尺寸数据
                document.getElementById('update-longSize').value = data.longSize || '';
                document.getElementById('update-widthSize').value = data.widthSize || '';
                document.getElementById('update-heightSize').value = data.heightSize || '';

                modal.dataset.currentId = item.id;
                modal.style.display = 'flex';
            }
        } catch (err) {
            console.error('加载详情失败:', err);
            alert(`数据加载失败: ${err.message}`);
        }
    }
    async function deleteCar(item) {
        if (!confirm(`确认删除船舶吗？`)) return;
        try {
            // 获取最新数据
            const res = await fetch(`http://localhost:8080/sys/ship/delete/${item}`);
            const response = await res.json();

            if (response.status === 0) {
                alert("删除成功")
                fetchData('query');
            }else {
                alert(`删除失败：${response.message || '未知错误'}`);
            }
        } catch (err) {
            console.error('加载详情失败:', err);
            alert(`数据加载失败: ${err.message}`);
        }
    }
    // 修改表单提交处理
    document.getElementById('modal-form-update').addEventListener('submit', async (e) => {
        e.preventDefault();
        const modal = document.getElementById('modal-mask-update');
        const id = modal.dataset.currentId;

        const formData = {
            id: id,
            supplierId: document.getElementById('update-supplierId').value,
            name: document.getElementById('update-name').value,
            phone: document.getElementById('update-phone').value,
            grossTon: parseFloat(document.getElementById('update-grossTon').value),
            loadTon: parseFloat(document.getElementById('update-loadTon').value),
            longSize: parseFloat(document.getElementById('update-longSize').value),
            widthSize: parseFloat(document.getElementById('update-widthSize').value),
            heightSize: parseFloat(document.getElementById('update-heightSize').value)
        };

        try {
            const res = await fetch('http://localhost:8080/sys/ship/update', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            });

            const response = await res.json();
            if (response.status === 0) {
                alert('修改成功');
                modal.style.display = 'none';
                fetchData('query');
            } else {
                alert('修改失败：' + (response.message || '未知错误'));
            }
        } catch (err) {
            console.error('提交失败:', err);
            alert('提交失败：' + err.message);
        }
    });

    async function selectAllWaterSupplier(item) {
        // const select = document.getElementById('form-select-supplier');
        const select = document.getElementById(item);
        // const select2 = document.getElementById('add-fleetId');
        // const updateSelect = document.getElementById('update-fleetId'); // 新增
        // try {
            const res = await fetch('http://localhost:8080/sys/waterway/selectAllWaterSupplier');
            const response = await res.json();

            if (response.status === 0) {
                // 先清空选项（保留第一个"全部"选项）
                select.innerHTML = '<option value="">全部</option>';

                // 动态添加供应商选项
                response.data.forEach(supplier => {
                    const option = document.createElement('option');
                    option.value = supplier.id;
                    option.textContent = supplier.name;
                    select.appendChild(option);
                    // select2.appendChild(option);
                    // updateSelect.appendChild(option.cloneNode(true)); // 克隆选项
                });
            } else {
                console.error('供应商加载失败:', response.message);
            }
        // } catch (err) {
        //     console.error('请求异常:', err);
        //     alert('供应商列表加载失败，请检查网络');
        // }
    }
    selectAllWaterSupplier('form-select-supplier');
    selectAllWaterSupplier('add-supplierId');
    selectAllWaterSupplier('update-supplierId');
    // 状态映射表
    const STATUS_MAP = {
        0: '空闲中',
        1: '待出航',
        2: '出航中'
    };

</script>
</body>
</html>